package vn.co.thn.android.store.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import vn.co.thn.android.store.NSConstants;
import vn.co.thn.android.store.NSUrlApi;
import vn.co.thn.android.store.R;
import vn.co.thn.android.store.data.NSLocationItemData;
import vn.co.thn.android.store.data.NSNewFeedItenData;
import vn.co.thn.android.store.data.NSUrlUploadItemData;
import vn.co.thn.android.store.util.NSParam;
import vn.co.thn.android.store.util.NSRequestService;
import vn.co.thn.android.store.util.NSRequestService.NSRequestServiceCAllBack;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.VolleyError;

public class NSPostFeedActivity extends NSCommonActivity {
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private Uri fileUri;
	private EditText address_target, content;
	private File file_upload;
	private NSLocationItemData location;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ns_post_feed_activity);
		address_target = (EditText) findViewById(R.id.address_target);
		content = (EditText) findViewById(R.id.content);
		findViewById(R.id.location).setOnClickListener(this);
		findViewById(R.id.camera).setOnClickListener(this);
		findViewById(R.id.gallery).setOnClickListener(this);
		findViewById(R.id.btn_post).setOnClickListener(this);
	}

	private void GetUrlPost() {
		NSRequestService geturl = new NSRequestService(NSUrlApi.Api_NewFeed_add, NSUrlUploadItemData.class, new ArrayList<NSParam>(),
				new NSRequestServiceCAllBack<NSUrlUploadItemData>() {

					@Override
					public void onResult(NSUrlUploadItemData data, boolean isUpdate) {
						// TODO Auto-generated method stub
						PostFeed(data.getUrl().replace("localhost", "10.0.3.2"));
					}

					@Override
					public void onResult(ArrayList<NSUrlUploadItemData> data, boolean isUpdate) {
						// TODO Auto-generated method stub
						PostFeed(data.get(0).getUrl().replace("localhost", "10.0.3.2"));
					}

					@Override
					public void onError(VolleyError error) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onException(Exception e) {
						// TODO Auto-generated method stub

					}
				});
		geturl.deleteCache();
		geturl.StartPost();
	}

	private void PostFeed(String url) {
		String androidId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
		ArrayList<NSParam> params = new ArrayList<NSParam>();
		params.add(new NSParam("Device_Id", androidId));
		params.add(new NSParam("Content", content.getText().toString()));
		params.add(new NSParam("lat", this.location.getLatitude()));
		params.add(new NSParam("log", this.location.getLongitude()));
		params.add(new NSParam("Address", address_target.getText().toString()));
		NSRequestService requestService = new NSRequestService(url, NSNewFeedItenData.class, params, new NSRequestServiceCAllBack<NSNewFeedItenData>() {

			@Override
			public void onResult(NSNewFeedItenData data, boolean isUpdate) {
				// TODO Auto-generated method stub
				finish();
			}

			@Override
			public void onResult(ArrayList<NSNewFeedItenData> data, boolean isUpdate) {
				// TODO Auto-generated method stub
				finish();
			}

			@Override
			public void onError(VolleyError error) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onException(Exception e) {
				// TODO Auto-generated method stub

			}
		}, this);
		requestService.deleteCache();
		requestService.StartMultipart(file_upload, "Image_Url");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.location:
			startActivityForResult(new Intent(this, NSSearchAddressActivity.class), NSConstants.SEARCH_ADDRESS_REQUEST_CODE);
			break;
		case R.id.camera:
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

			startActivityForResult(intent, NSConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
			break;
		case R.id.gallery:
			Intent gralley = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(gralley, NSConstants.GALLERY_REQUEST_CODE);
			break;
		case R.id.btn_post:
			GetUrlPost();
			break;
		default:
			break;
		}
	}

	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image or video */
	@SuppressLint("SimpleDateFormat")
	private static File getOutputMediaFile(int type) {
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}

		return mediaFile;
	}

	private String getRealPathFromURI(Uri contentURI) {
		String result;
		Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
		if (cursor == null) { // Source is Dropbox or other similar local file
								// path
			result = contentURI.getPath();
		} else {
			cursor.moveToFirst();
			int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
			result = cursor.getString(idx);
			cursor.close();
		}
		return result;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == NSConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				ImageView img = (ImageView) findViewById(R.id.imageView1);
				img.setImageURI(fileUri);
				file_upload = new File(getRealPathFromURI(fileUri));
			}
		}
		if (requestCode == NSConstants.GALLERY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				ImageView img = (ImageView) findViewById(R.id.imageView1);
				fileUri = data.getData();
				img.setImageURI(fileUri);
				file_upload = new File(getRealPathFromURI(fileUri));
			}
		}
		if (requestCode == NSConstants.SEARCH_ADDRESS_REQUEST_CODE) {
			address_target.setVisibility(View.VISIBLE);
			location = (NSLocationItemData) data.getSerializableExtra(NSConstants.ADDRESS_SEARCH);
			address_target.setText(location.getAddress());
		}
	}
}
